import useTabStore from '@/store/tab';
import { createBrowserHistory, Location } from 'history';
import { useMemo } from 'react';
import { matchRoutes } from 'react-router-config';
import { useLocation } from 'react-router-dom';
import createRouteProvider from './createRouteProvider';
import { getDevNavs } from './development';
import routes from './routes';

const filterUrl = ['/logout', '/redirect', '/login'];
// TODO 优化history存储方式
if (!window.reactHistory) {
  window.reactHistory = createBrowserHistory();
}
const history = window.reactHistory;
const listen = (location: Location) => {
  const matchedRoutes = matchRoutes(routes, location.pathname);
  const { route } = matchedRoutes[matchedRoutes.length - 1];
  const actives = matchedRoutes.map((i) => i.match.path);
  document.title = route.meta?.title || 'phm';
  const tabState = useTabStore.getState();
  // if (match.path === '/*') {
  //   tabState.setActiveTab(route.path);
  //   return;
  // }
  if (!filterUrl.includes(location.pathname)) {
    // const cacheRoutes = matchedRoutes.map(({ route: r }: any) => ({
    //   path: r.path,
    //   meta: r.meta,
    //   name: r.name
    // }));
    // if (!isEqual(cacheRoutes, tabState.matchedRoutes)) {
    //   tabState.setMatchRoutes(cacheRoutes);
    // }
    if (actives.length > 1 && actives.includes('/')) {
      actives.shift();
    }
    tabState.setActiveTab(actives);
  }
};
history.listen(listen);
// 初始化调用
listen(history.location);
const RouteProvider = createRouteProvider(history);
const useQuery = () => {
  const { search } = useLocation();

  return useMemo(() => new URLSearchParams(search), [search]);
};

export * from 'react-router-dom';
export { RouteProvider, history, matchRoutes, getDevNavs, useQuery };
